package com.example.managemyself.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.example.managemyself.R;
// import com.example.managemyself.ui.weather.WeatherSearchActivity;
import com.example.managemyself.util.DateManager;
import com.example.managemyself.util.OpenWeatherHelper;
import com.example.managemyself.util.LocationHelper;
import com.example.managemyself.util.WeatherCacheManager;
import com.example.managemyself.MainActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 主页Fragment
 */
public class HomeFragment extends Fragment implements DateManager.DateChangeListener {

    private HomeViewModel homeViewModel;
    private DateManager dateManager;
    private OpenWeatherHelper weatherHelper;
    private LocationHelper locationHelper;
    private WeatherCacheManager weatherCacheManager;
    
    // UI组件
    private TextView tvCurrentDate;
    private TextView tvDayOfWeek;
    private TextView tvTaskCount;
    private TextView tvDiaryStatus;
    private TextView tvHealthStatus;
    private TextView tvWeatherInfo;
    private TextView tvWeatherCity;
    private TextView tvWeatherTemp;
    private TextView tvWeatherDesc;
    private Button btnUpdateWeather;
    private CardView cardWeather;
    private CardView cardTasks;
    private CardView cardDiary;
    private CardView cardHealth;
    
    private View root; // 保存根视图引用
    
    // 日期格式化
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    private SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.getDefault());

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        
        initViews(root);
        setupDateManager();
        setupClickListeners();
        initWeatherServices();
        
        // 初始化天气显示
        updateWeatherDisplay("汕尾", "--°C", "点击更新天气获取最新信息");
        loadWeatherData();
        
        return root;
    }
    
    private void initViews(View root) {
        this.root = root; // 保存根视图引用
        
        // 日期相关
        tvCurrentDate = root.findViewById(R.id.tv_selected_date);
        
        // 天气相关
        tvWeatherCity = root.findViewById(R.id.tv_weather_city);
        tvWeatherTemp = root.findViewById(R.id.tv_weather_temp);
        tvWeatherDesc = root.findViewById(R.id.tv_weather_desc);
        btnUpdateWeather = root.findViewById(R.id.btn_update_weather);
        
        // 统计信息（使用其他控件临时显示）
        tvTaskCount = root.findViewById(R.id.tv_almanac_title);
        tvDiaryStatus = root.findViewById(R.id.tv_almanac_yi);
        tvHealthStatus = root.findViewById(R.id.tv_almanac_ji);
        
        // 卡片
        cardWeather = root.findViewById(R.id.card_weather);
        cardTasks = root.findViewById(R.id.card_pomodoro);
        cardDiary = root.findViewById(R.id.card_date_navigation);
        cardHealth = root.findViewById(R.id.card_almanac);
        
        // 新增：日期导航控件
        TextView tvSelectedDate = root.findViewById(R.id.tv_selected_date);
        Button btnSelectDate = root.findViewById(R.id.btn_select_date);
        
        // 设置日期选择按钮点击事件
        if (btnSelectDate != null) {
            btnSelectDate.setOnClickListener(v -> showDatePicker());
        }
        
        // 如果tvCurrentDate不存在，使用新的日期显示控件
        if (tvCurrentDate == null) {
            tvCurrentDate = tvSelectedDate;
        }
    }
    
    private void setupDateManager() {
        dateManager = DateManager.getInstance();
        dateManager.addDateChangeListener(this);
        
        // 初始化显示当前日期
        updateDateDisplay(dateManager.getSelectedDate());
    }
    
    private void setupClickListeners() {
        // 天气更新按钮点击
        if (btnUpdateWeather != null) {
            btnUpdateWeather.setOnClickListener(v -> {
                forceUpdateWeather();
            });
        }
        
        // 日期点击 - 显示日期选择器
        if (tvCurrentDate != null) {
            tvCurrentDate.setOnClickListener(v -> showDatePicker());
        }
        
        // 黄历卡片点击
        CardView cardAlmanac = root.findViewById(R.id.card_almanac);
        if (cardAlmanac != null) {
            cardAlmanac.setOnClickListener(v -> {
                // 跳转到黄历详情页面
                Intent intent = new Intent(getActivity(), com.example.managemyself.ui.almanac.AlmanacDetailActivity.class);
                startActivity(intent);
            });
        }
        
        // 功能卡片点击事件
        setupFunctionCardListeners();
    }
    
    private void setupFunctionCardListeners() {
        // 番茄钟卡片
        CardView cardPomodoro = root.findViewById(R.id.card_pomodoro);
        if (cardPomodoro != null) {
            cardPomodoro.setOnClickListener(v -> {
                // 跳转到番茄钟页面
                if (getActivity() != null) {
                    ((MainActivity) getActivity()).navigateToPomodoro();
                }
            });
        }
        
        // 身体状态卡片
        CardView cardBodyStatus = root.findViewById(R.id.card_body_status);
        if (cardBodyStatus != null) {
            cardBodyStatus.setOnClickListener(v -> {
                // 跳转到健康页面
                if (getActivity() != null) {
                    ((MainActivity) getActivity()).navigateToHealth();
                }
            });
        }
        
        // 轮盘卜卦卡片
        CardView cardRoulette = root.findViewById(R.id.card_roulette);
        if (cardRoulette != null) {
            cardRoulette.setOnClickListener(v -> {
                // 跳转到轮盘页面
                if (getActivity() != null) {
                    ((MainActivity) getActivity()).navigateToRoulette();
                }
            });
        }
    }
    
    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        Date currentDate = dateManager != null ? dateManager.getSelectedDate() : new Date();
        if (currentDate != null) {
            calendar.setTime(currentDate);
        }
        
        android.app.DatePickerDialog datePickerDialog = new android.app.DatePickerDialog(
            requireContext(),
            (view, year, month, dayOfMonth) -> {
                Calendar selectedCalendar = Calendar.getInstance();
                selectedCalendar.set(year, month, dayOfMonth, 0, 0, 0);
                selectedCalendar.set(Calendar.MILLISECOND, 0);
                
                Date newDate = selectedCalendar.getTime();
                
                // 通过DateManager设置日期，这会自动通知所有监听器
                if (dateManager != null) {
                    dateManager.setSelectedDate(newDate);
                }
                
                // 显示选择的日期
                showToast("已选择日期: " + dateFormat.format(newDate));
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        );
        
        datePickerDialog.show();
    }
    
    @Override
    public void onDateChanged(Date newDate) {
        updateDateDisplay(newDate);
    }
    
    private void updateDateDisplay(Date date) {
        if (tvCurrentDate != null) {
            tvCurrentDate.setText(dateFormat.format(date));
        }
        
        // 更新其他统计信息
        updateStatistics();
    }
    
    private void updateStatistics() {
        // 更新任务统计
        if (tvTaskCount != null) {
            tvTaskCount.setText("今日任务: 0/0");
        }
        
        // 更新日记状态
        if (tvDiaryStatus != null) {
            tvDiaryStatus.setText("今日日记: 未记录");
        }
        
        // 更新健康状态
        if (tvHealthStatus != null) {
            tvHealthStatus.setText("健康状态: 良好");
        }
    }
    
    /**
     * 初始化天气服务
     */
    private void initWeatherServices() {
        if (getContext() != null) {
            weatherHelper = OpenWeatherHelper.getInstance();
            weatherHelper.initialize(getContext());
            
            locationHelper = new LocationHelper(getContext());
            weatherCacheManager = WeatherCacheManager.getInstance(getContext());
        }
    }
    
    /**
     * 加载天气数据
     */
    private void loadWeatherData() {
        if (locationHelper == null || weatherHelper == null) {
            showToast("天气服务初始化失败");
            updateWeatherDisplay("汕尾", "--°C", "服务初始化失败");
            return;
        }
        
        // 检查天气服务是否可用
        if (!weatherHelper.isServiceAvailable()) {
            showToast("天气服务暂时不可用");
            updateWeatherDisplay("汕尾", "--°C", "服务暂时不可用");
            return;
        }
        
        updateWeatherDisplay("定位中", "--°C", "正在获取位置...");
        
        try {
            locationHelper.getCurrentLocation(new LocationHelper.LocationCallback() {
                @Override
                public void onLocationReceived(double latitude, double longitude) {
                    // 获取到位置后获取天气
                    updateWeatherDisplay("定位成功", "--°C", "正在获取天气...");
                    try {
                        weatherHelper.getCurrentWeatherByLocation(latitude, longitude, new OpenWeatherHelper.WeatherCallback() {
                            @Override
                            public void onWeatherSuccess(OpenWeatherHelper.WeatherInfo weatherInfo) {
                                updateWeatherDisplay(weatherInfo.cityName, weatherInfo.temperature + "°C", weatherInfo.weatherText);
                            }
                            
                            @Override
                            public void onError(String error) {
                                showToast("当前位置天气获取失败，切换到汕尾");
                                // 自动切换到汕尾天气
                                loadDefaultCityWeather();
                            }
                        });
                    } catch (Exception e) {
                        showToast("天气服务异常，切换到汕尾");
                        loadDefaultCityWeather();
                    }
                }
                
                @Override
                public void onError(String error) {
                    showToast("位置获取失败，切换到汕尾");
                    // 使用默认城市（汕尾）
                    loadDefaultCityWeather();
                }
            });
        } catch (Exception e) {
            showToast("定位服务异常，切换到汕尾");
            loadDefaultCityWeather();
        }
    }
    
    /**
     * 强制更新天气数据（忽略缓存）
     */
    private void forceUpdateWeather() {
        if (weatherCacheManager != null) {
            // 清除缓存，强制从网络获取最新数据
            weatherCacheManager.clearCache();
        }
        
        // 重新加载天气数据
        loadDefaultCityWeather();
    }
    
    /**
     * 加载默认城市天气（汕尾）
     */
    private void loadDefaultCityWeather() {
        // 尝试多个汕尾的英文名称
        String[] cityNames = {"汕尾", "Shanwei", "ShanWei", "Haifeng"};
        loadWeatherWithFallback(cityNames, 0);
    }
    
    /**
     * 使用多个城市名称尝试获取天气数据
     */
    private void loadWeatherWithFallback(String[] cityNames, int currentIndex) {
        if (currentIndex >= cityNames.length) {
            // 所有城市名称都尝试失败，显示默认信息
            updateWeatherDisplay("汕尾", "--°C", "天气服务暂时不可用");
            return;
        }
        
        String cityName = cityNames[currentIndex];
        updateWeatherDisplay(cityName, "--°C", "正在获取天气...");
        
        try {
            weatherHelper.getCurrentWeatherByCity(cityName, new OpenWeatherHelper.WeatherCallback() {
                @Override
                public void onWeatherSuccess(OpenWeatherHelper.WeatherInfo weatherInfo) {
                    // 成功获取天气数据
                    updateWeatherDisplay("汕尾", weatherInfo.temperature + "°C", weatherInfo.weatherText);
                    
                    // 缓存成功的城市名称
                    if (weatherCacheManager != null) {
                        weatherCacheManager.cacheWeather("汕尾", weatherInfo);
                    }
                    
                    showToast("天气数据已更新");
                }
                
                @Override
                public void onError(String error) {
                    // 当前城市名称失败，尝试下一个
                    if (currentIndex < cityNames.length - 1) {
                        loadWeatherWithFallback(cityNames, currentIndex + 1);
                    } else {
                        // 所有尝试都失败
                        updateWeatherDisplay("汕尾", "--°C", "天气获取失败");
                        showToast("天气服务暂时不可用，请稍后重试");
                    }
                }
            });
        } catch (Exception e) {
            // 服务异常，尝试下一个城市名称
            if (currentIndex < cityNames.length - 1) {
                loadWeatherWithFallback(cityNames, currentIndex + 1);
            } else {
                updateWeatherDisplay("汕尾", "--°C", "服务异常");
                showToast("天气服务异常");
            }
        }
    }
    
    /**
     * 使用缓存机制加载天气数据
     */
    private void loadWeatherWithCache(String cityName) {
        if (weatherCacheManager == null || weatherHelper == null) {
            updateWeatherDisplay(cityName, "--°C", "服务初始化失败");
            return;
        }
        
        // 首先检查缓存
        OpenWeatherHelper.WeatherInfo cachedWeather = weatherCacheManager.getCachedWeather(cityName);
        if (cachedWeather != null) {
            // 使用缓存数据
            updateWeatherDisplay(cachedWeather.cityName, cachedWeather.temperature + "°C", cachedWeather.weatherText);
            long remainingTime = weatherCacheManager.getCacheRemainingTime();
            showToast("使用缓存数据，" + remainingTime + "分钟后可更新");
            return;
        }
        
        // 缓存无效，从网络获取
        if (!weatherHelper.isServiceAvailable()) {
            updateWeatherDisplay(cityName, "--°C", "服务暂时不可用");
            return;
        }
        
        // 对于汕尾，使用回退机制
        if ("汕尾".equals(cityName)) {
            loadDefaultCityWeather();
        } else {
            // 其他城市直接请求
            updateWeatherDisplay(cityName, "--°C", "正在获取天气...");
            
            try {
                weatherHelper.getCurrentWeatherByCity(cityName, new OpenWeatherHelper.WeatherCallback() {
                    @Override
                    public void onWeatherSuccess(OpenWeatherHelper.WeatherInfo weatherInfo) {
                        // 更新显示
                        updateWeatherDisplay(weatherInfo.cityName, weatherInfo.temperature + "°C", weatherInfo.weatherText);
                        
                        // 缓存数据
                        weatherCacheManager.cacheWeather(cityName, weatherInfo);
                        showToast("天气数据已更新");
                    }
                    
                    @Override
                    public void onError(String error) {
                        showToast(cityName + "天气获取失败: " + error);
                        updateWeatherDisplay(cityName, "--°C", "天气获取失败");
                    }
                });
            } catch (Exception e) {
                showToast("天气服务暂时不可用");
                updateWeatherDisplay(cityName, "--°C", "服务暂时不可用");
            }
        }
    }
    
    /**
     * 更新天气显示
     */
    private void updateWeatherDisplay(String city, String temperature, String description) {
        if (tvWeatherCity != null) {
            tvWeatherCity.setText(city);
        }
        if (tvWeatherTemp != null) {
            tvWeatherTemp.setText(temperature);
        }
        if (tvWeatherDesc != null) {
            tvWeatherDesc.setText(description);
        }
    }
    
    /**
     * 显示Toast提示信息
     */
    private void showToast(String message) {
        if (getContext() != null) {
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (dateManager != null) {
            dateManager.removeDateChangeListener(this);
        }
        if (weatherHelper != null) {
            weatherHelper.release();
        }
    }
} 